// 员工首页内容区域组件（图表整合版）
Vue.component('employee-home-content', {
  data() {
    return {
      // 统计数据
      attendanceDays: 0,
      lateCount: 0,
      lastPerformance: 0,
      loading: true,
      
      // 图表实例
      attendancePieChart: null,
      performanceChart: null,
      
      // 本月考勤状态数据
      attendanceStatusData: [
        { name: '正常出勤', value: 0 },
        { name: '迟到', value: 0 },
        { name: '早退', value: 0 },
        { name: '缺勤', value: 0 }
      ],
      
      // 年度绩效趋势数据
      performanceTrendData: {
        months: [],
        scores: []
      }
    };
  },
  
  mounted() {
    this.loadPersonalData();
  },
  
  beforeDestroy() {
    // 销毁图表实例
    if (this.attendancePieChart) {
      this.attendancePieChart.dispose();
    }
    if (this.performanceChart) {
      this.performanceChart.dispose();
    }
  },
  
  methods: {
    // 加载个人数据概览
    async loadPersonalData() {
      this.loading = true;
      try {
        const response = await statisticsAPI.getPersonalOverview();
        const data = response.data;
        
        // 设置考勤数据
        this.attendanceDays = data.attendance_summary.attendance_days;
        this.lateCount = data.attendance_summary.late_count;
        this.attendanceStatusData = data.attendance_summary.status_distribution;
        
        // 设置绩效数据
        this.lastPerformance = data.performance_summary.last_performance;
        this.performanceTrendData = data.performance_summary.yearly_trend;
        
        // 数据加载完成后初始化图表
        this.$nextTick(() => {
          this.initCharts();
        });
        
      } catch (error) {
        console.error('加载个人数据失败:', error);
        this.$message.error('数据加载失败，使用模拟数据');
        this.generateMockData();
      } finally {
        this.loading = false;
      }
    },

    // 加载真实数据（保留作为备用）
    async loadData() {
      this.loading = true;
      
      try {
        // 加载本月考勤数据
        await this.loadAttendanceData();
        
        // 加载年度绩效数据
        await this.loadPerformanceData();
      } catch (error) {
        console.error('加载数据失败:', error);
        this.$message.error('数据加载失败，使用模拟数据');
        // 如果API调用失败，使用模拟数据
        this.generateMockData();
      }
      
      this.loading = false;
    },

    // 生成模拟数据（备用）
    generateMockData() {
      this.loading = true;
      
      // 模拟本月考勤数据
      this.generateAttendanceMockData();
      
      // 模拟年度绩效数据
      this.generatePerformanceMockData();
      
      // 模拟数据生成完成后初始化图表
      this.$nextTick(() => {
        this.initCharts();
      });
      
      this.loading = false;
    },

    // 加载考勤数据
    async loadAttendanceData() {
      try {
        const response = await statisticsAPI.getMonthlyStatus();
        const data = response.data;
        
        this.attendanceDays = data.attendance_days;
        this.lateCount = data.late_count;
        this.attendanceStatusData = data.status_distribution;
      } catch (error) {
        console.error('加载考勤数据失败:', error);
        throw error;
      }
    },

    // 加载绩效数据
    async loadPerformanceData() {
      try {
        const response = await performanceAPI.getYearlyTrend();
        const data = response.data;
        
        this.lastPerformance = data.last_performance;
        this.performanceTrendData = {
          months: data.months,
          scores: data.scores
        };
      } catch (error) {
        console.error('加载绩效数据失败:', error);
        throw error;
      }
    },
    
    // 生成考勤模拟数据
    generateAttendanceMockData() {
      // 模拟本月考勤状态分布
      const normalDays = Math.floor(Math.random() * 15) + 15; // 15-29天正常出勤
      const lateDays = Math.floor(Math.random() * 5) + 1; // 1-5天迟到
      const earlyDays = Math.floor(Math.random() * 3) + 1; // 1-3天早退
      const absentDays = Math.floor(Math.random() * 3); // 0-2天缺勤
      
      this.attendanceDays = normalDays;
      this.lateCount = lateDays;
      
      this.attendanceStatusData = [
        { name: '正常出勤', value: normalDays },
        { name: '迟到', value: lateDays },
        { name: '早退', value: earlyDays },
        { name: '缺勤', value: absentDays }
      ];
    },
    
    // 生成绩效模拟数据
    generatePerformanceMockData() {
      const months = [];
      const scores = [];
      
      // 生成过去4个季度的绩效数据（每3个月考核一次）
      const currentYear = new Date().getFullYear();
      const currentMonth = new Date().getMonth() + 1;
      
      // 计算当前季度
      const currentQuarter = Math.ceil(currentMonth / 3);
      
      // 生成过去4个季度的数据
      for (let i = 3; i >= 0; i--) {
        const quarterMonth = currentQuarter - i;
        let year = currentYear;
        let month = quarterMonth * 3 - 2; // 每季度的第一个月（1, 4, 7, 10）
        
        // 处理跨年情况
        if (month <= 0) {
          year--;
          month += 12;
        }
        
        const monthStr = `${year}-${String(month).padStart(2, '0')}`;
        months.push(monthStr);
        
        // 生成模拟绩效分数（75-95分之间，有波动）
        const baseScore = 88;
        const variation = (Math.random() - 0.5) * 15; // -7.5到+7.5的波动
        const score = Math.max(75, Math.min(95, Math.round(baseScore + variation)));
        scores.push(score);
      }
      
      // 设置最近绩效分
      this.lastPerformance = scores[scores.length - 1];
      
      this.performanceTrendData = {
        months,
        scores
      };
    },
    
    // 初始化图表
    initCharts() {
      this.initAttendancePieChart();
      this.initPerformanceChart();
    },
    
    // 初始化本月考勤饼图
    initAttendancePieChart() {
      const chartDom = document.getElementById('attendancePieChart');
      if (!chartDom) return;
      
      this.attendancePieChart = echarts.init(chartDom);
      
      const option = {
        title: {
          text: '本月考勤状态分布',
          left: 'center',
          top: '5%',
          textStyle: {
            fontSize: 20,
            fontWeight: '600',
            color: '#2c3e50',
            fontFamily: 'Microsoft YaHei, sans-serif'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}<br/>天数: {c}天<br/>占比: {d}%',
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e0e0e0',
          borderWidth: 1,
          borderRadius: 8,
          textStyle: {
            color: '#333',
            fontSize: 14
          },
          extraCssText: 'box-shadow: 0 4px 12px rgba(0,0,0,0.15);'
        },
        legend: {
          orient: 'vertical',
          left: '8%',
          top: '25%',
          itemGap: 20,
          textStyle: {
            fontSize: 14,
            color: '#555',
            fontFamily: 'Microsoft YaHei, sans-serif'
          },
          formatter: (name) => {
            const item = this.attendanceStatusData.find(d => d.name === name);
            return item ? `${name} (${item.value}天)` : name;
          }
        },
        series: [
          {
            name: '考勤状态',
            type: 'pie',
            radius: ['50%', '80%'],
            center: ['65%', '55%'],
            data: this.attendanceStatusData.filter(item => item.value > 0),
            emphasis: {
              itemStyle: {
                shadowBlur: 15,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              },
              scale: true,
              scaleSize: 5
            },
            itemStyle: {
              borderRadius: 12,
              borderColor: '#fff',
              borderWidth: 3,
              shadowBlur: 5,
              shadowColor: 'rgba(0, 0, 0, 0.1)'
            },
            label: {
              show: false
            },
            labelLine: {
              show: false
            }
          }
        ],
        color: ['#36cfc9', '#ff9c6e', '#ff7875', '#bae7ff']
      };
      
      this.attendancePieChart.setOption(option);
    },
    
    // 初始化年度绩效趋势图
    initPerformanceChart() {
      const chartDom = document.getElementById('performanceTrendChart');
      if (!chartDom) return;
      
      this.performanceChart = echarts.init(chartDom);
      
      const option = {
        title: {
          text: '年度绩效趋势',
          left: 'center',
          top: '5%',
          textStyle: {
            fontSize: 20,
            fontWeight: '600',
            color: '#2c3e50',
            fontFamily: 'Microsoft YaHei, sans-serif'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#1890ff',
              width: 1,
              type: 'dashed'
            }
          },
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderColor: '#e0e0e0',
          borderWidth: 1,
          borderRadius: 8,
          textStyle: {
            color: '#333',
            fontSize: 14
          },
          extraCssText: 'box-shadow: 0 4px 12px rgba(0,0,0,0.15);',
          formatter: function(params) {
            const data = params[0];
            return `${data.name}<br/>绩效分数: ${data.value}分`;
          }
        },
        grid: {
          left: '8%',
          right: '8%',
          top: '20%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.performanceTrendData.months.map(month => {
            // 处理季度格式：2024-Q4 -> 2024年Q4
            if (month.includes('-Q')) {
              const [year, quarter] = month.split('-Q');
              return `${year}年Q${quarter}`;
            }
            // 处理月份格式：2024-01 -> 2024年1月
            else if (month.includes('-')) {
              const [year, monthNum] = month.split('-');
              return `${year}年${parseInt(monthNum)}月`;
            }
            // 其他格式直接返回
            return month;
          }),
          axisLabel: {
            fontSize: 13,
            color: '#666',
            fontFamily: 'Microsoft YaHei, sans-serif'
          },
          axisLine: {
            lineStyle: {
              color: '#e0e0e0',
              width: 1
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '绩效分数',
          min: 70,
          max: 100,
          interval: 10,
          axisLabel: {
            fontSize: 13,
            color: '#666',
            fontFamily: 'Microsoft YaHei, sans-serif',
            formatter: '{value}分'
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#f5f5f5',
              type: 'dashed'
            }
          },
          nameTextStyle: {
            color: '#666',
            fontSize: 13,
            fontFamily: 'Microsoft YaHei, sans-serif'
          }
        },
        series: [
          {
            name: '绩效分数',
            type: 'line',
            data: this.performanceTrendData.scores,
            smooth: true,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 4,
              color: '#1890ff'
            },
            itemStyle: {
              color: '#1890ff',
              borderColor: '#fff',
              borderWidth: 3,
              shadowBlur: 8,
              shadowColor: 'rgba(24, 144, 255, 0.3)'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(24, 144, 255, 0.2)'
                }, {
                  offset: 1, color: 'rgba(24, 144, 255, 0.05)'
                }]
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 15,
                shadowColor: 'rgba(24, 144, 255, 0.5)',
                scale: true,
                scaleSize: 2
              }
            },
            markPoint: {
              data: [
                { type: 'max', name: '最高分', symbol: 'pin', symbolSize: 50 },
                { type: 'min', name: '最低分', symbol: 'pin', symbolSize: 50 }
              ],
              itemStyle: {
                color: '#ff4d4f',
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                color: '#fff',
                fontSize: 12,
                fontWeight: 'bold'
              }
            },
            markLine: {
              data: [
                { 
                  type: 'average', 
                  name: '平均分',
                  lineStyle: {
                    color: '#52c41a',
                    type: 'dashed',
                    width: 2
                  },
                  label: {
                    color: '#52c41a',
                    fontSize: 12,
                    fontWeight: 'bold'
                  }
                }
              ]
            }
          }
        ]
      };
      
      this.performanceChart.setOption(option);
    }
  },
  
  template: `
    <div style="padding: 32px; max-width: 1200px; margin: 0 auto;">
      <!-- 数据概览卡片 -->
      <el-card shadow="hover" style="margin-bottom: 24px;">
        <div style="margin-bottom: 24px;">
          <div style="font-size: 22px; font-weight: bold;">个人数据概览</div>
        </div>
        
        <!-- 数据统计行 -->
        <el-row :gutter="20" style="margin-bottom: 24px;">
          <el-col :span="8">
            <el-statistic 
              title="本月出勤天数" 
              :value="attendanceDays" 
              suffix="天"
              :loading="loading">
            </el-statistic>
          </el-col>
          <el-col :span="8">
            <el-statistic 
              title="本月迟到次数" 
              :value="lateCount" 
              suffix="次"
              :loading="loading">
            </el-statistic>
          </el-col>
          <el-col :span="8">
            <el-statistic 
              title="近期绩效分" 
              :value="lastPerformance" 
              suffix="分"
              :loading="loading">
            </el-statistic>
          </el-col>
        </el-row>
      </el-card>
      
      <!-- 图表区域 -->
      <el-row :gutter="20">
        <!-- 本月考勤饼图 -->
        <el-col :span="12">
          <el-card shadow="hover" style="height: 450px;">
            <div id="attendancePieChart" style="width: 100%; height: 400px;"></div>
          </el-card>
        </el-col>
        
        <!-- 年度绩效趋势图 -->
        <el-col :span="12">
          <el-card shadow="hover" style="height: 450px;">
            <div id="performanceTrendChart" style="width: 100%; height: 400px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  `
});